package com.immunology.core;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;
import java.util.List;

import com.immunology.database.ConnectionManager;
import com.immunology.database.DbColumns;

public abstract class BaseDao<T> implements GenericDao<T>{

	private BaseTransformer<T> transformer;
	protected ConnectionManager connectionManager = new ConnectionManager();
	// protected AnnotationGetter annotationGetter = new AnnotationGetter();
	protected String tableName;

	// public BaseDao(BaseTransformer<T> transformer, T obj) {
	// this.transformer = transformer;
	// tableName = annotationGetter.getTableName(obj);
	// }

	public BaseDao(BaseTransformer<T> transformer, String tableName) {
		this.transformer = transformer;
		this.tableName = tableName;
	}

	public BaseDao() {
	}

	public T getById(int id) {
		T result = null;
		Connection connection = connectionManager.getConnection();
		ResultSet resultSet = null;
		StringBuilder query = new StringBuilder();
		query.append("SELECT * FROM ");
		query.append(tableName);
		query.append(" WHERE ID = ?");
		try {
			PreparedStatement preparedStatement = connection.prepareStatement(query
					.toString());
			preparedStatement.setInt(DbColumns.FIRST_COLUMN, id);
			resultSet = preparedStatement.executeQuery();
			if (resultSet.next()) {
				result = transformer.transformTo(resultSet);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			connectionManager.closeConnection(connection);
		}
		return result;
	}

	public List<T> getAll() {
		List<T> result = new LinkedList<T>();
		Connection connection = connectionManager.getConnection();
		ResultSet resultSet = null;
		StringBuilder query = new StringBuilder();
		query.append("SELECT * FROM ");
		query.append(tableName);
		try {
			Statement statement = connection.createStatement();
			resultSet = statement.executeQuery(query.toString());
			while (resultSet.next()) {
				result.add(transformer.transformTo(resultSet));
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			connectionManager.closeConnection(connection);
		}
		return result;
	}

	public boolean delete(int id) {
		boolean result = false;
		Connection connection = connectionManager.getConnection();
		StringBuilder query = new StringBuilder();
		query.append("DELETE FROM ");
		query.append(tableName);
		query.append(" WHERE ID = ?");
		try {
			PreparedStatement preparedStatement = (PreparedStatement) connection
					.prepareStatement(query.toString());
			preparedStatement.setInt(DbColumns.FIRST_COLUMN, id);
			preparedStatement.executeUpdate();
			result = true;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			connectionManager.closeConnection(connection);
		}
		return result;
	}

}
